package com.market.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.market.base.model.Quote;
import com.market.base.utils.WebUtils;
import com.market.model.Manager;
import com.market.model.Position;
import com.market.service.ManagerService;
import com.market.service.PositionService;
import com.market.utils.ListUtils;
import com.market.utils.QuoteUtils;

/**
 * 持仓信息控制类
 * @author java
 *
 */
@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
	@Autowired
	private PositionService positionService;
	@Autowired
	private ManagerService managerService; 

	@RequestMapping({"/", "/index"})
	public String index(HttpServletRequest request, Model model) {
		Manager manager = this.getSessionUser(request);
		if(manager != null ){
			return "/index";
		}else{
			return "redirect:/login";
		}
	}
	
	/**
	 * 跳转到持仓信息添加页面
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add() {
		return "/admin/add";
	}
	
	/**
	 * 持仓信息添加页面
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(Position position, HttpServletRequest request, Model model) {
		positionService.insert(position);
		return "redirect:/admin/"+position.getId()+"/details";
	}
	
	/**
	 * 跳转到持仓信息修改页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	public String edit(@PathVariable int id, Model model) {
		Position position = positionService.findPositionById(id);
		if(position!=null) {
			model.addAttribute("position", position);
			return "/admin/edit";
		}
		return error(model, "信息不存在", "持仓信息不存在");
	}
	
	/**
	 * 修改持仓信息
	 * @param position
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String edit(Position position, Model model) {
		if(position!=null) {
			boolean fln = positionService.update(position);
			if(!fln) return error(model, "操作失败", "更新持仓信息失败");
		
			return "redirect:/admin/" + position.getId() + "/details";
		}
		return error(model, "操作失败", "更新持仓信息失败");
	}
	
	@RequestMapping(value = "/{id}/details", method = RequestMethod.GET)
	public String details(@PathVariable int id, Model model) {
		Position position = positionService.findPositionById(id);
		if(position!=null) {
			model.addAttribute("position", position);
		}
		
		return "/admin/details";
	}
	
	
	/**
	 * 持仓列表和账户列表		
	 * @param request
	 * @param position
	 * @param model
	 * @return
	 */
	@RequestMapping({"/ls"})
	public String list(HttpServletRequest request, Position position, Model model) {
		List<Position> positionList =  positionService.findPositionList();
		List<Manager> managerList = managerService.findManagerList();
		List<Position> pList = new ArrayList<Position>();
		List<Manager> mList = new ArrayList<Manager>();
		float profitLoss = 0;
		float closePositionPrice = QuoteUtils.getNewQuote(); //最新价格（平仓人价）
		if(ListUtils.isNotEmpty(positionList)) {
			for(Position p : positionList) {
				Integer buyOrSell = p.getBuyOrSell();
				Float openPositionPrice = p.getOpenPositionPrice();	//持仓价
				float  curProfitLoss = 0; //当日浮动盈亏
				if(buyOrSell == 0) {//买入
					//买入：当日浮动盈亏=(平仓价-持仓价)*15
					curProfitLoss = (closePositionPrice - openPositionPrice) * 15;
				}
				else if(buyOrSell == 1) {//卖出
					//卖出：当日浮动盈亏=(持仓价-平仓价)*15
					curProfitLoss = (openPositionPrice - closePositionPrice) * 15;
				}
				profitLoss += curProfitLoss;
				p.setClosePositionPrice(closePositionPrice);
				p.setCurProfitLoss(curProfitLoss);
				
				pList.add(p);
			}
		}
		
		if(ListUtils.isNotEmpty(managerList)) {
			for(Manager m : managerList) {
				m.setProfitLoss(profitLoss);
				//当前权益 = 期初权益+浮动盈亏
				m.setCurProfit(m.getPrimeProfit() + profitLoss);
				mList.add(m);
			}
		}
		model.addAttribute("positionList", pList);
		model.addAttribute("managerList", mList);
		return "/admin/list";
	}
	
	/**
	 * 输出Json格式字符串
	 * @return
	 */
	@RequestMapping({"/jsondata"})
	@ResponseBody
	public String jsondata() {
		List<Position> positionList =  positionService.findPositionList();
		List<Manager> managerList = managerService.findManagerList();
		List<Position> pList = new ArrayList<Position>();
		List<Manager> mList = new ArrayList<Manager>();
		float profitLoss = 0;
		float closePositionPrice = QuoteUtils.getNewQuote(); //最新价格（平仓人价）
		if(ListUtils.isNotEmpty(positionList)) {
			for(Position p : positionList) {
				Integer buyOrSell = p.getBuyOrSell();
				Float openPositionPrice = p.getOpenPositionPrice();	//持仓价
				float  curProfitLoss = 0; //当日浮动盈亏
				if(buyOrSell == 0) {//买入
					//买入：当日浮动盈亏=(平仓价-持仓价)*15
					curProfitLoss = (closePositionPrice - openPositionPrice) * 15;
				}
				else if(buyOrSell == 1) {//卖出
					//卖出：当日浮动盈亏=(持仓价-平仓价)*15
					curProfitLoss = (openPositionPrice - closePositionPrice) * 15;
				}
				profitLoss += curProfitLoss;
				p.setClosePositionPrice(closePositionPrice);
				p.setCurProfitLoss(curProfitLoss);
				
				pList.add(p);
			}
		}
		
		if(ListUtils.isNotEmpty(managerList)) {
			for(Manager m : managerList) {
				m.setProfitLoss(profitLoss);
				//当前权益 = 期初权益+浮动盈亏
				m.setCurProfit(m.getPrimeProfit() + profitLoss);
				mList.add(m);
			}
		}
		
		SimplePropertyPreFilter[] filters = {new SimplePropertyPreFilter(Manager.class, 
				"userCode",
				"userName",
				"primeProfit",
				"curProfit",
				"money",
				"profitLoss",
				"profitLossTotal",
				"canDeposit",
				"curFeeTotal",
				"occupyDeposit",
				"preDelayFee",
				"riskRate",
				"freezeDeposit",
				"freezeFee",
				"accountStatus"
				),
				new SimplePropertyPreFilter(Position.class, 
						"positionNo",
						"goodsName",
						"buyOrSell",
						"buildPosition",
						"openPosition",
						"buildPositionPrice",
						"openPositionPrice",
						"closePositionPrice",
						"stopLossPrice",
						"stopProfitPrice",
						"curProfitLoss",
						"ratio",
						"occupyDeposit",
						"createTime",
						"phoneDealer")};
		
		Quote quote = new Quote();
		quote.setManageList(mList);
		quote.setPositionList(positionList);
		
		return JSONObject.toJSONString(quote, filters);
	}
	
	/**
	 * 跳转到文件上传页面
	 * @return
	 */
	@RequestMapping(value = "upload", method = RequestMethod.GET)
	public String upload() {
		return "/admin/upload";
	}
}
